package com.jianganming.proxy;

import sun.misc.ProxyGenerator;

import java.io.FileOutputStream;
import java.lang.reflect.Proxy;

public class TeacherProxy {
    public Object getIncetance(Object obj){
        //这里使用类匿名内部类的方式实现了InvocationHandler的invoke方法逻辑
        return Proxy.newProxyInstance(obj.getClass().getClassLoader(),
                obj.getClass().getInterfaces(),(obj0,method,args)->{
                    System.out.println("代理类工作开始");
                    Object result = method.invoke(obj, args);
                    System.out.println("代理类工作结束");
                    return result;
                });
    }

    public static void main(String[] args) {
        TeacherLi teacherLi = new TeacherLi();
        TeacherProxy proxy = new TeacherProxy();
        Object incetance = proxy.getIncetance(teacherLi);
        System.out.println(incetance);
        String hello = ((HelloWorld)incetance).hello("小明");
        System.out.println(hello);
        String wang = ((HelloTeacher)incetance).teach("王老师");
        System.out.println(wang);
        /*try {
            //生成动态代理的源代码
            byte[] bytes = ProxyGenerator.generateProxyClass("$Proxy0", new Class[]{HelloWorld.class});
            FileOutputStream out =new FileOutputStream("/Users/jianganming/Downloads/$Proxy0.class");
            out.write(bytes);
            out.close();
        }catch (Exception e){
            e.printStackTrace();
        }*/


        /*HelloTeacher helloTeacher = (HelloTeacher) obj;
        String teach = helloTeacher.teach("小红");
        System.out.println(teach);*/
    }
}
